var page = 1;
var cursor = 0;
var since = 0;
var max_id = 0;
var loading = false;
var finished = false;
var mmo = false;
var showat = false;
var lcat = false;
var atpos = 0;
var atsl=false;
var atu = "";
var isgpressed = false;
var newWeiboHeight;
var canvas;
var context;
var drawLine = false;
var lastMouseX;
var lastMouseY;
var canvasLeft;
var canvasTop;
var scrolling = false;
var unreadPost = false;
var hmenu = [];

function showImage(url){
	window.open(url);
}

function getPost(page, uname, cache){
	var el = document.getElementById("topNotice");
	el.innerHTML = "载入中……";
	el.style.display = "block";
	loading = true;
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		showTopNotice("载入中……");
  		if(!xmlhttp.responseText){
  			finished = true;
  			document.getElementById("timeLineLoading").style.display = "none";
  			return;
  		}
  		else{
  			el = document.createElement("div");
  			el.innerHTML = xmlhttp.responseText;
  			document.getElementById("timeLine").appendChild(el);
  			setTimeout(function(){loading = false;document.getElementById("timeLineLoading").style.display = "none";if(!finished){document.getElementById("moreTimeLine").style.display = "block";}}, 500);
  		}
		}
	}
	if(!max_id){
		max_id = document.getElementById("max_id")?document.getElementById("max_id").innerHTML:0;
	}
	if(cache){
	xmlhttp.open("GET","/timeline.php?cache=&max="+max_id+"&since="+since+"&page="+page+(uname?"&name="+uname:"")+(q?"&search="+q:"")+(ty?"&type="+ty:"")+(trend?"&trend="+trend:""));
	}
	else{
		xmlhttp.open("GET","/timeline.php?max="+max_id+"&since="+since+"&page="+page+(uname?"&name="+uname:"")+(q?"&search="+q:"")+(ty?"&type="+ty:"")+(trend?"&trend="+trend:""));
	}
	xmlhttp.send();
}

function getCommentline(page, type){
	var el = document.getElementById("topNotice");
	el.innerHTML = "载入中……";
	el.style.display = "block";
	loading = true;
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		showTopNotice("载入中……");
  		if(!xmlhttp.responseText){
  			finished = true;
  			document.getElementById("timeLineLoading").style.display = "none";
  			return;
  		}
  		else{
  			el = document.createElement("div");
  			el.innerHTML = xmlhttp.responseText;
  			document.getElementById("timeLine").appendChild(el);
  	  	setTimeout(function(){loading = false;document.getElementById("timeLineLoading").style.display = "none";if(page >= 5 && !finished){document.getElementById("moreTimeLine").style.display = "block";}}, 500);
  	  }
		}
	}
	xmlhttp.open("GET","/commentline.php?request=1&type="+type+"&max="+max_id+"&since="+since+"&page="+page);
	xmlhttp.send();
}

function getComments(page){
	var el = document.getElementById("topNotice");
	el.innerHTML = "载入中……";
	el.style.display = "block";
	loading = true;
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		showTopNotice("载入中……");
  		if(!xmlhttp.responseText){
  			finished = true;
  			document.getElementById("timeLineLoading").style.display = "none";
  			return;
  		}
  		document.getElementById("comment").innerHTML += xmlhttp.responseText;
  	  setTimeout(function(){loading = false;document.getElementById("timeLineLoading").style.display = "none";if(page >= 5 && !finished){document.getElementById("moreTimeLine").style.display = "block";}}, 500);
		}
	}
	xmlhttp.open("GET","/comments.php?request=1&post="+post+"&max="+max_id+"&since="+since+"&page="+page);
	xmlhttp.send();
}

function getFriends(tcursor){
	if(!tcursor){
		setTimeour(function(){document.getElementById('timeLineLoading').style.display='none';},100);
		return;
	}
	var el = document.getElementById("topNotice");
	el.innerHTML = "载入中……";
	el.style.display = "block";
	loading = true;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if(xmlhttp.readyState==4 && xmlhttp.status==200){
  		showTopNotice("载入中……");
  	  document.getElementById("timeLine").innerHTML += xmlhttp.responseText;
  	  setTimeout(function(){
  	  	loading = false;
  	  	var cursorDiv = document.getElementsByName("cursor");
				var cursorLatest = cursorDiv[cursorDiv.length-1];
  	  	document.getElementById("timeLineLoading").style.display = "none";
  	  	if(page >= 5 && !finished && tcursor != parseInt(cursorLatest.innerHTML)){
  	  		cursor = parseInt(cursorLatest.innerHTML);
  	  		document.getElementById("moreTimeLine").style.display = "block";
  	  	}
  	  }, 500);
		}
	}
	xmlhttp.open("GET","/friends.php?friendships="+friendships+"&name="+uname+"&cursor="+tcursor);
	xmlhttp.send();
}

function getRestHeight(doAction, cache){
	var pageTop = document.getElementById('timeLine').offsetHeight;
	var outerTop = document.body.scrollTop || document.documentElement.scrollTop;
	var restHeight = pageTop-outerTop;
	if(document.getElementById('sidebarNoticeFloat') && document.getElementById('sidebarNoticeFloat').offsetTop && outerTop >= document.getElementById('sidebarNoticeFloat').offsetTop-50 && document.getElementById('sidebarNotice')){
		document.getElementById('sidebarNotice').style.display = "block";
		document.getElementById('sidebarad').style.display = "block";
	}
	else if(document.getElementById('sidebarNoticeFloat') && document.getElementById('sidebarNoticeFloat').offsetTop && outerTop < document.getElementById('sidebarNoticeFloat').offsetTop-50 && document.getElementById('sidebarNotice')){
		document.getElementById('sidebarNotice').style.display = "none";
		document.getElementById('sidebarad').style.display = "none";
	}
	if(restHeight <= 2700 && !loading && page<5 && !finished){
		page++;
		if(document.getElementById("moreTimeLine")){
			document.getElementById("moreTimeLine").style.display = "none";
		}
		if(document.getElementById("timeLineLoading")){
			document.getElementById("timeLineLoading").style.display = "block";
		}
		if(doAction == "comments"){
			getComments(page);
		}
		else if(doAction == "commentline"){
			getCommentline(page, "comments");
		}
		else if(doAction == "sentcommentline"){
			getCommentline(page, "sentcomments");
		}
		else if(doAction == "mentioncommentline"){
			getCommentline(page, "mentioncomments");
		}
		else if(doAction == "friendship"){
			var cursorDiv = document.getElementsByName("cursor");
			var cursorLatest = cursorDiv[cursorDiv.length-1];
			if(!cursorLatest || cursor == parseInt(cursorLatest.innerHTML)){
				finished = true;
				document.getElementById("timeLineLoading").style.display = "none";
				document.getElementById("moreTimeLine").style.display = "block";
				return;
			}
			else{
 				cursor = parseInt(cursorLatest.innerHTML);
 				getFriends(cursor);
 			}
		}
		else{
			getPost(page, uname, cache);
		}
	}
}

function replayComment(boxId, userName, dataId, commentId){
	var replayBox = document.getElementById(boxId);
	replayBox.innerHTML = "回复@"+userName+"<span class='cancelReplay' onclick='document.getElementById(\""+boxId+"\").style.display=\"none\";document.getElementById(\""+boxId+"\").innerHTML=\"\";document.getElementById(\""+dataId+"\").innerHTML=\"\";'>×</span>";
	replayBox.style.display = "table-cell";
	var dataBox = document.getElementById(dataId);
	dataBox.innerHTML = commentId;
}

function postnew(post, repost, image, jump){
	if(!post && !repost){
		return;
	}
	post = post?post:"";
	repost = repost?repost:"";
	image = image?image:"";
	var content = "status="+encodeURIComponent(post)+"&repost="+repost+"&image="+image;
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.open("POST", "/postnew.php", true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			if(document.getElementById("share")){
				document.getElementById("share").style.background = "";
			}
			if(xmlhttp.responseText.length<10){
				var errorMessage = getErrorMessage(xmlhttp.responseText);
				showMessageBox(errorMessage,1,null,"确定",null,closeMessageBox);
				showTopNotice("发布失败");
			}
			else{
				if(jump){
					showTopNotice("发布成功");
				}
				else{
					showTopNotice("发布成功");
					getNewWeibo(0);
				}
			}
  	}
  }
  xmlhttp.send(content);
}

function sendStatus(statusText, repost, image, jump){
	if(!statusText || statusText=="分享身边的新鲜事……"){
		showMessageBox("请输入您要分享的内容",1,null,"确定",null,closeMessageBox);
		return;
	}
	var statusBox = document.getElementById("b");
	var checkBox = document.getElementById("checkBox");
	if(statusBox && checkBox){
		statusBox.value = "分享身边的新鲜事……";
		statusBox.style.color = "#888";
		checkBox.innerHTML = "";
		document.getElementById("faceDiv").innerHTML = "";
		document.getElementById("share").style.background = "url(/images/publishing.gif) no-repeat center center";
	}
	postnew(statusText, repost, image, jump);
}

function checkWords(f){
	bId = f?"f_b":"b";
	cbId = f?"f_checkBox":"checkBox";
	var statusBox = document.getElementById(bId);
	var checkBox = document.getElementById(cbId);
	if(statusBox.value.length){
		checkBox.innerHTML = 140-statusBox.value.length;
		if(140-statusBox.value.length<0){
			checkBox.style.color = "#DD4B39";
		}
		else{
			checkBox.style.color = "#888888";
		}
	}
	else{
		checkBox.innerHTML = "";
	}
}

function repost(postId, post){
	document.getElementById("shareTag").style.display = "block";
	document.getElementById("shareRepost").innerHTML = postId;
	var shareBox = document.getElementById("b");
	shareBox.style.color = "#000";
	shareBox.value = " "+post;
	if(shareBox.setSelectionRange)
	{
		shareBox.focus();
		shareBox.setSelectionRange(0,0);
	}
	else if (shareBox.createTextRange) {
		var range = shareBox.createTextRange();
		range.collapse(true);
		range.moveEnd('character', 0);
		range.moveStart('character', 0);
		range.select();
	}
}

function replaynew(postid, comment, replay, postpage, listid, jump){
	if(!postid || (!comment && !replay)){
		return;
	}
	var el = document.getElementById("topNotice");
	el.innerHTML = "发送中……";
	el.style.display = "block";
	comment = comment?comment:"";
	replay = replay?replay:"";
	listid = listid?listid:"comments"
	var content = "postid="+postid+"&comment="+encodeURIComponent(comment)+"&replay="+replay;
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.open("POST", "/replaynew.php?postpage="+postpage, true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			if(xmlhttp.responseText.length<10){
				errorMessage = getErrorMessage(xmlhttp.responseText);
				showMessageBox(errorMessage,1,null,"确定",null,closeMessageBox);
				showTopNotice("发布失败");
			}
			else{
				document.getElementById(listid).innerHTML = xmlhttp.responseText + document.getElementById(listid).innerHTML;
			}
			if(replay){
				showTopNotice("回复成功");
			}
			else{
				showTopNotice("评论成功");
			}
  	}
  }
  xmlhttp.send(content);
}

function getNewMessage(){
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if(xmlhttp.readyState==4 && xmlhttp.status==200){
  		if(xmlhttp.responseText){
  			var message;
  			try{
  				message = JSON.parse(xmlhttp.responseText);
  			}
  			catch(e){}
  			if(message["cmt"]){
  				document.getElementById("cmtNum").innerHTML = message["cmt"]
  				document.getElementById("cmtNum").style.display = "block";
  				document.getElementById("cmtRevNum").innerHTML = message["cmt"]
  				document.getElementById("cmtRevNum").style.display = "block";
  			}
  			else{
  				document.getElementById("cmtNum").style.display = "none";
  				document.getElementById("cmtNum").innerHTML = "";
  				document.getElementById("cmtRevNum").style.display = "none";
  				document.getElementById("cmtRevNum").innerHTML = "";
  			}
  			if(message["msg"]){
  				document.getElementById("msgNum").innerHTML = message["msg"]
  				document.getElementById("msgNum").style.display = "block";
  			}
  			else{
  				document.getElementById("msgNum").style.display = "none";
  				document.getElementById("msgNum").innerHTML = "";
  			}
  			if(message["mtn"]){
  				document.getElementById("mtnWeiboNum").innerHTML = message["mtn"]
  				document.getElementById("mtnWeiboNum").style.display = "block";
  			}
  			else{
  				document.getElementById("mtnWeiboNum").style.display = "none";
  				document.getElementById("mtnWeiboNum").innerHTML = "";
  			}
  			if(message["mtnc"]){
  				document.getElementById("mtnCommentNum").innerHTML = message["mtnc"]
  				document.getElementById("mtnCommentNum").style.display = "block";
  			}
  			else{
  				document.getElementById("mtnCommentNum").style.display = "none";
  				document.getElementById("mtnCommentNum").innerHTML = "";
  			}
  			if(message["mtn"] || message["mtnc"]){
  				document.getElementById("mtnNum").innerHTML = Number(message["mtn"]) + Number(message["mtnc"]);
  				document.getElementById("mtnNum").style.display = "block";
  			}
  			else{
  				document.getElementById("mtnNum").style.display = "none";
  				document.getElementById("mtnNum").innerHTML = "";
  			}
  		}
  	}
	}
	xmlhttp.open("GET","/getmessages.php");
	xmlhttp.send();
}

function getPosition(a) {
    var b = 0;
    void 0 != a.selectionStart ? b = a.selectionStart: (b = document.selection.createRange(), b.moveStart("character", -a.value.length), b = b.text.length);
    return b
}

function setPosition(obj, pos) { 
    if(obj.createTextRange) { 
        var range = obj.createTextRange(); 
        range.move("character", pos); 
        range.select(); 
    } else if(obj.selectionStart) { 
        obj.focus(); 
        obj.setSelectionRange(pos, pos); 
    } 
}

function insertTrend(tar){
	if(tar.value=="分享身边的新鲜事……"){
		tar.style.color = "#000";
		tar.value = "";
	}
	var mp = getPosition(tar);
	tar.value = tar.value.substring(0, mp) + "##" + tar.value.substring(mp, tar.value.length);
	setPosition(tar, mp + 1);
}

function insertFace(face,f){
	elId = f?"f_b":"b";
	var tar = document.getElementById(elId);
	if(tar.value=="分享身边的新鲜事……"){
		tar.style.color = "#000";
		tar.value = "";
	}
	var mp = getPosition(tar);
	tar.value = tar.value.substring(0, mp) + face + tar.value.substring(mp, tar.value.length);
	setPosition(tar, mp + face.length);
}

function showFaces(page,f){
	elId = f?"f_faceDiv":"faceDiv";
	document.getElementById(elId).style.display = "block";
	var facesdiv = "<div style='height: 100px;'>";
	for(i=(page-1)*45; i<faces.length && i<(page)*45; i+=15){
		facesdiv += "<div>";
		for(j=0; j+i<faces.length && j<15; j++){
			k = i+j;
			if("https:" == document.location.protocol){
				facesdiv += "<div class='facesGif'><a href='#' onclick='insertFace(\""+faces[k]+"\","+f+");return false;'><img style='width: 22px; height: 22px;' src='/qsimg/"+base64encode(faceurl[k])+"' /></a></div>";
			}
			else{
				facesdiv += "<div class='facesGif'><a href='#' onclick='insertFace(\""+faces[k]+"\","+f+");return false;'><img style='width: 22px; height: 22px;' src='"+faceurl[k]+"' /></a></div>";
			}
		}
		facesdiv += "<div style='clear: both'></div></div>";
	}
	facesdiv += "</div>";
	if(page != 1){
		if(page*45 < faces.length){
			facesdiv += "<div class='facesAction'><a href='#' onclick='showFaces("+(page-1)+","+f+");return false;'>上一页</a> | <a href='#' onclick='showFaces("+(page+1)+","+f+");return false;'>下一页</a></div>";
		}
		else{
			facesdiv += "<div class='facesAction'><a href='#' onclick='showFaces("+(page-1)+","+f+");return false;'>上一页</a></div>";
		}
	}
	else if(page*45 < faces.length){
		facesdiv += "<div class='facesAction'><a href='#' onclick='showFaces("+(page+1)+","+f+");return false;'>下一页</a></div>";
	}
	document.getElementById(elId).innerHTML = facesdiv;
}

function showFacesAction(f){
	elId = f?"f_faceDiv":"faceDiv";
	if(document.getElementById(elId).innerHTML == ""){
		showFaces(1,f);
	}
	else{
		document.getElementById(elId).innerHTML = "";
	}
}

function showMessageBox(messageText, buttonSelect, leftButtonText, rightButtonText, leftButtonFunction, rightButtonFunction) {
	document.getElementById("messageBox").innerHTML = messageText;
	if(leftButtonText){
		document.getElementById("leftMessageButton").innerHTML = leftButtonText;
	}
	if(rightButtonText){
		document.getElementById("rightMessageButton").innerHTML = rightButtonText;
	}
	if(buttonSelect == 0){
		document.getElementById("leftMessageButton").style.display = "inline";
		document.getElementById("rightMessageButton").style.display = "none";
	}
	else if(buttonSelect == 1){
		document.getElementById("leftMessageButton").style.display = "none";
		document.getElementById("rightMessageButton").style.display = "inline";
	}
	else{
		document.getElementById("leftMessageButton").style.display = "inline";
		document.getElementById("rightMessageButton").style.display = "inline";
	}
	if(leftButtonFunction){
		document.getElementById("leftMessageButton").onclick = leftButtonFunction;
	}
	if(rightButtonFunction){
		document.getElementById("rightMessageButton").onclick = rightButtonFunction;
	}
	document.getElementById("messageBackground").style.display="block";
}

function closeMessageBox(){
	document.getElementById("messageBackground").style.display="none";
}

function getErrorMessage(errorCode){
	errorCode = parseInt(errorCode);
	var code = new Array(10001,10002,10003,10004,10005,10006,10007,10008,10009,10010,10011,10012,10013,10014,10016,10017,10018,10020,10021,10022,10023,10024,20001,20002,20003,20005,20006,20007,20008,20009,20012,20013,20014,20015,20016,20017,20018,20019,20020,20021,20022,20031,20032,20101,20102,20103,20104,20109,20111,20201,20202,20203,20204,20301,20302,20303,20305,20306,20307,20401,20402,20501,20502,20503,20505,20506,20601,20602,20603,20604,20605,20606,20607,20608,20610,20611,20612,20613,20614,20615);
	var message = new Array("系统错误","服务暂停","远程服务错误","IP限制不能请求该资源","该资源需要appkey拥有授权","缺少source (appkey) 参数","不支持的MediaType (%s)","参数错误，请参考API文档","任务过多，系统繁忙","任务超时","RPC错误","非法请求","不合法的微博用户","应用的接口访问权限受限","缺失必选参数 (%s)，请参考API文档","参数值非法，需为 (%s)，实际为 (%s)，请参考API文档","请求长度超过限制","接口不存在","请求的HTTP方法不支持","IP请求频次超过上限","用户请求频次超过上限","用户请求特殊接口 (%s) 频次超过上限","IDs参数为空","Uid参数为空","用户不存在","不支持的图片类型，仅仅支持JPG、GIF、PNG","图片太大","请确保使用multpart上传图片","内容为空","IDs参数太长了","输入文字太长，请确认不超过140个字符","输入文字太长，请确认不超过300个字符","安全检查参数有误，请再调用一次","账号、IP或应用非法，暂时无法完成此操作","发布内容过于频繁","提交相似的信息","包含非法网址","提交相同的信息","包含广告信息","包含非法内容","此IP地址上的行为异常","需要验证码","发布成功，目前服务器可能会有延迟，请耐心等待1-2分钟","您无权进行此操作","不是你发布的微博","不能转发自己的微博","不合法的微博","微博ID为空","不能发布相同的微博","不存在的微博评论","不合法的评论","不是你发布的评论","评论ID为空","不能给不是你粉丝的人发私信","不合法的私信","不是属于你的私信","不存在的私信","不能发布相同的私信","非法的私信ID","域名不存在","Verifier错误","参数source_user或者target_user的用户不存在","必须输入目标用户id或者screen_name","参数user_id必须是你关注的用户","加关注请求超过上限","已经关注此用户","列表名太长，请确保输入的文本不超过10个字符","列表描叙太长，请确保输入的文本不超过70个字符","列表不存在","不是列表的所属者","列表名或描叙不合法","记录已存在","数据库错误，请联系系统管理员","列表名冲突","目前不支持私有分组","创建列表失败","目前只支持私有分组","订阅列表达到上限","创建列表达到上限，请参考API文档","列表成员上限，请参考API文档");
	for(i=0; i<code.length; i++){
		if(code[i] == errorCode){
			return message[i];
		}
	}
	return "未知错误";
}

function addFavorites(postId){
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		if(!xmlhttp.responseText){
  			showMessageBox("参数不正确",1,null,"确定",null,closeMessageBox);
  			return;
  		}
  		else if(parseInt(xmlhttp.responseText) == 1){
  			showTopNotice("收藏成功");
  		}
  		else{
  			var errorMessage = getErrorMessage(xmlhttp.responseText);
				showMessageBox(errorMessage,1,null,"确定",null,closeMessageBox);
  		}
		}
	}
	xmlhttp.open("GET","/addfav.php?id="+postId);
	xmlhttp.send();
}

function removeFavorites(postId){
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		if(!xmlhttp.responseText){
  			showMessageBox("参数不正确",1,null,"确定",null,closeMessageBox);
  			return;
  		}
  		else if(parseInt(xmlhttp.responseText) == 1){
  			fadeout(document.getElementById("post-"+postId),1);
  		}
  		else{
  			var errorMessage = getErrorMessage(xmlhttp.responseText);
				showMessageBox(errorMessage,1,null,"确定",null,closeMessageBox);
  		}
		}
	}
	xmlhttp.open("GET","/removefav.php?id="+postId);
	xmlhttp.send();
}

function deletePost(postId,jump){
	showMessageBox("确实要删除这条微博吗？",2,"取消","确定",closeMessageBox,function(){comfirmDel(postId,jump);closeMessageBox();});
}

function comfirmDel(postId,jump){
	var el = document.getElementById("topNotice");
	el.innerHTML = "删除中……";
	el.style.display = "block";
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		if(!xmlhttp.responseText){
  			showMessageBox("参数不正确",1,null,"确定",null,closeMessageBox);
  			return;
  		}
  		else if(parseInt(xmlhttp.responseText) == 1){
  			if(jump){
  				location.href = "/";
  			}
  			else{
  				showTopNotice("删除成功");
  				fadeout(document.getElementById("post-"+postId),1);
  			}
  		}
  		else{
  			var errorMessage = getErrorMessage(xmlhttp.responseText);
				showMessageBox(errorMessage,1,null,"确定",null,closeMessageBox);
  		}
		}
	}
	xmlhttp.open("GET","/deletePost.php?id="+postId);
	xmlhttp.send();
}

function delComment(commentId){
	showMessageBox("确实要删除这条评论吗？",2,"取消","确定",closeMessageBox,function(){confirmDelComment(commentId);closeMessageBox();});
}

function confirmDelComment(commentId){
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		if(!xmlhttp.responseText){
  			showMessageBox("参数不正确",1,null,"确定",null,closeMessageBox);
  			return;
  		}
  		else if(parseInt(xmlhttp.responseText) == 1){
  			fadeout(document.getElementById("comment_"+commentId),1);
  		}
  		else{
  			var errorMessage = getErrorMessage(xmlhttp.responseText);
				showMessageBox(errorMessage,1,null,"确定",null,closeMessageBox);
  		}
		}
	}
	xmlhttp.open("GET","/deletecomment.php?id="+commentId);
	xmlhttp.send();
}

function getimage(url){
	document.getElementById("imageUploadShow").innerHTML = "<img src='" + url + "' />";
	url = url.replace(/\+/g, "%2B");
	document.getElementById("imageDiv").value = url;
}

function showimagetag(){
	document.getElementById("imageTag").style.display = "block";
}

function showimageuploading(){
	document.getElementById("share").style.background = "url(/images/imageloading.gif) no-repeat center center";
}

function hideimageuploading(){
	document.getElementById("share").style.background = "";
}

function fadeout(el,o){
	el.style.opacity = o;
	el.style.filter = "Alpha(opacity="+o*10+")";
	o-=0.1;
	if(o>0.1){
		setTimeout(function(){fadeout(el,o);},80);
	}
	else{
		el.style.display = "none";
		el.innerHTML = "";
		el.style.opacity = 1;
		el.style.filter = "Alpha(opacity=10)";
	}
}

function removeFriend(userId){
	showMessageBox("确实要取消关注此用户吗？",2,"取消","确定",closeMessageBox,function(){confirmRemFriend(userId);closeMessageBox();});
}

function removeFollower(userId){
	showMessageBox("确实要移除此粉丝吗？",2,"取消","确定",closeMessageBox,function(){confirmRemFollower(userId);closeMessageBox();});
}

function confirmRemFriend(userId){
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		if(!xmlhttp.responseText){
  			showMessageBox("参数不正确",1,null,"确定",null,closeMessageBox);
  			return;
  		}
  		else if(parseInt(xmlhttp.responseText) == 1){
  			fadeout(document.getElementById("user-"+userId),1);
  		}
  		else{
  			var errorMessage = getErrorMessage(xmlhttp.responseText);
				showMessageBox(errorMessage,1,null,"确定",null,closeMessageBox);
  		}
		}
	}
	xmlhttp.open("GET","/removefriend.php?id="+userId);
	xmlhttp.send();
}

function confirmRemFollower(userId){
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		if(!xmlhttp.responseText){
  			showMessageBox("参数不正确",1,null,"确定",null,closeMessageBox);
  			return;
  		}
  		else if(parseInt(xmlhttp.responseText) == 1){
  			fadeout(document.getElementById("user-"+userId),1);
  		}
  		else{
  			var errorMessage = getErrorMessage(xmlhttp.responseText);
				showMessageBox(errorMessage,1,null,"确定",null,closeMessageBox);
  		}
		}
	}
	xmlhttp.open("GET","/removefollower.php?id="+userId);
	xmlhttp.send();
}

function removeFriendInPage(userId,el){
	showMessageBox("确实要取消关注此用户吗？",2,"取消","确定",closeMessageBox,function(){confirmRemFriendInPage(userId,el);closeMessageBox();});
}

function confirmRemFriendInPage(userId,el){
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		if(!xmlhttp.responseText){
  			showMessageBox("参数不正确",1,null,"确定",null,closeMessageBox);
  			return;
  		}
  		else if(parseInt(xmlhttp.responseText) == 1){
  			el.innerHTML = "添加关注";
  			el.className = "followButton";
  			el.onclick = function(){
  				follow(userId,this);
  			}
  		}
  		else{
  			var errorMessage = getErrorMessage(xmlhttp.responseText);
				showMessageBox(errorMessage,1,null,"确定",null,closeMessageBox);
  		}
		}
	}
	xmlhttp.open("GET","/removefriend.php?id="+userId);
	xmlhttp.send();
}

function follow(userId,el){
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		if(!xmlhttp.responseText){
  			showMessageBox("参数不正确",1,null,"确定",null,closeMessageBox);
  			return;
  		}
  		else if(parseInt(xmlhttp.responseText) == 1){
  			showMessageBox("已经关注此用户",1,null,"确定",null,closeMessageBox);
  			el.innerHTML = "取消关注";
  			el.className = "unfollowButton";
  			el.onclick = function(){
  				removeFriendInPage(userId,this);
  			}
  		}
  		else{
  			var errorMessage = getErrorMessage(xmlhttp.responseText);
				showMessageBox(errorMessage,1,null,"确定",null,closeMessageBox);
  		}
		}
	}
	xmlhttp.open("GET","/follow.php?id="+userId);
	xmlhttp.send();
}

function doPos(){
	var minWidth = "v"=="\v"?500:505
	var wHWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.offsetWidth)/2;
	wHWidth = wHWidth<minWidth?minWidth:wHWidth;
	var wHHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.offsetHeight)/2;
	var msgBoxLeft = wHWidth - 266;
	var msgBoxTop = wHHeight - 200;
	document.getElementById("messageBoxDiv").style.left = msgBoxLeft + "px";
	document.getElementById("messageBoxDiv").style.top = msgBoxTop + "px";
	canvasLeft = wHWidth - 200;
	canvasTop = wHHeight - 150;
	document.getElementById("canvasDiv").style.left = canvasLeft + "px";
	document.getElementById("canvasDiv").style.top = canvasTop + "px";
}

function showpublic(){
	showMessageBox("清爽版微博托管于Sina App Engine，由Sneezry.com提供技术支持。清爽版微博在外观设计上一定程度参考了<a target=\"_blank\" href=\"https://plus.google.com/\">Google+</a>的外观设计，并在部分布局中使用了<a target=\"_blank\" href=\"https://plus.google.com/\">Google+</a>的源代码。",0,"关闭",null,closeMessageBox,null);
}

function showqr(url){
	showMessageBox("<img style='margin: -20px 0 -20px 140px' src='http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl="+url+"' />",0,"关闭",null,closeMessageBox,null);
}

function publishAction(){
	if(!document.getElementById('f_b').value){
		return false;
	}
	sendStatus(document.getElementById('f_b').value,document.getElementById('f_shareRepost').innerText,'',1);
	document.getElementById('f_shareTag').style.display='none';
	document.getElementById('f_shareRepost').innerHTML='';
	closeMessageBox();
	var el = document.getElementById("topNotice");
	el.innerHTML = "发布中……";
	el.style.display = "block";
}

function showPublishBox(postId, post){
	showMessageBox("<div><div id=\"f_share\" style=\"float:none\" class=\"publishBoxOutline\"><textarea id=\"f_b\" "+((post || postId)?"style=\"color:#000 \"":"")+"class=\"publishBox\" onfocus=\"checkWords(1);checkat(1);if(this.value=='分享身边的新鲜事……'){this.style.color='#000';this.value='';}\" onblur=\"if(this.value==''){this.style.color='#888';this.value='分享身边的新鲜事……'}\" oninput=\"setTimeout(function(){checkWords(1);checkat(1);},100);\" onpopertychange=\"checkWords(1);checkat(1);\" onblur=\"showat = false;lcat=false;\">"+((post || postId)?" "+post:"分享身边的新鲜事……")+"</textarea><div "+(postId?" "+"style=\"display:block\" ":"")+"class=\"shareTag\" id=\"f_shareTag\">转发<span class=\"cancelShareTag\" onclick=\"document.getElementById('f_shareTag').style.display='none';document.getElementById('f_shareRepost').innerHTML='';\">×</span></div><div id=\"f_shareRepost\" style=\"display: none;\">"+(postId?postId:"")+"</div><div class=\"shareBoxIcons\"><div id=\"f_checkBox\" class=\"checkBox\"></div><div class=\"shareBoxIconsFace\" onclick=\"showFacesAction(1);return false;\"></div><div class=\"shareBoxIconsTopic\" onclick=\"insertTrend(document.getElementById('f_b'));\"></div><div class=\"floatClear\"></div></div><div class=\"floatClear\"></div></div><div id=\"f_faceDiv\"></div>",2,"关闭","发布",closeMessageBox,publishAction);
	var shareBox = document.getElementById('f_b');
	shareBox.focus();
	if(post){
		checkWords(1);
		if(shareBox.setSelectionRange){
			shareBox.setSelectionRange(0,0);
		}
		else if (shareBox.createTextRange) {
			var range = shareBox.createTextRange();
			range.collapse(true);
			range.moveEnd('character', 0);
			range.moveStart('character', 0);
			range.select();
		}
	}
}

function checkat(f){
	var bId = f?"f_b":"b";
	var wb = document.getElementById(bId).value;
	var nowchar = getPosition(document.getElementById(bId));
	var i;
	var nowatp = 0;
	if(!wb || lcat && wb.substr(nowchar-1,1)!="@" && (nowchar<1 || nowchar>1 && wb.substr(nowchar-2,1)!="@")){
		lcat = false;
		showat = false;
	}
	if(wb.substr(nowchar-1,1)=="@"){
		showat = true;
		lcat = true;
		atpos = getPosition(document.getElementById(bId));
		hideatsuggest();
	}
	else{
		lcat = false;
	}
	if(wb.substr(nowchar-1,1)==" "){
		showat = false;
	}
	if(showat && !lcat){
		for(i=0; i<nowchar; i++){
			if(wb.substr(i,1)=="@"){
				nowatp = i;
			}
		}
		atu = wb.substr(nowatp+1,nowchar-1);
		if(atu){
			showatsuggest(atu, getPosition(document.getElementById(bId)),f);
		}
	}
	else{
		hideatsuggest();
	}
}

function showatsuggest(q, p, f){
	bId = f?"f_b":"b";
	var wb = document.getElementById(bId).value;
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		var ats = JSON.parse(xmlhttp.responseText);
  		if(ats["ats"].length>0){
  			var atl = "";
  			for(i=0; i<ats["ats"].length; i++){
  				var re = eval("/"+q+"/ig")
  				atl += "<div class=\"atSuggestList\" onclick=\"insertat('"+ats["ats"][i]+"',"+p+","+f+")\">"+ats["atr"][i].replace(re, "<b>$&</b>")+"</div>";
  			}
  			document.getElementById("ats").innerHTML = atl;
  			var bp = kingwolfofsky.getInputPositon(document.getElementById(bId));
  			var atsleft = bp.left - 20;
  			var atstop = bp.top + 22;
  			document.getElementById("ats").style.left = atsleft + "px";
  			document.getElementById("ats").style.top = atstop + "px";
  			document.getElementById("ats").style.display = "block";
  		}
  		else{
  			hideatsuggest();
  		}
		}
	}
	xmlhttp.open("GET","/getatsuggest.php?q="+q);
	xmlhttp.send();
}

function hideatsuggest(){
	document.getElementById("ats").style.display = "none";
}

function insertat(n, p, f){
	bId = f?"f_b":"b";
	var tar = document.getElementById(bId);
	tar.value = tar.value.substring(0, atpos) + n + " " + tar.value.substring(p, tar.value.length);
	showat = false;
	hideatsuggest();
	var mp =atpos + n.length + 1;
	setPosition(tar, mp);
}

var kingwolfofsky = {
    getInputPositon: function (elem) {
        if (document.selection) {
            elem.focus();
            var Sel = document.selection.createRange();
            return {
                left: Sel.boundingLeft,
                top: Sel.boundingTop,
                bottom: Sel.boundingTop + Sel.boundingHeight
            };
        } else {
            var that = this;
            var cloneDiv = '{$clone_div}', cloneLeft = '{$cloneLeft}', cloneFocus = '{$cloneFocus}', cloneRight = '{$cloneRight}';
            var none = '<span style="white-space:pre-wrap;"> </span>';
            var div = elem[cloneDiv] || document.createElement('div'), focus = elem[cloneFocus] || document.createElement('span');
            var text = elem[cloneLeft] || document.createElement('span');
            var offset = that._offset(elem), index = this._getFocus(elem), focusOffset = { left: 0, top: 0 };

            if (!elem[cloneDiv]) {
                elem[cloneDiv] = div, elem[cloneFocus] = focus;
                elem[cloneLeft] = text;
                div.appendChild(text);
                div.appendChild(focus);
                document.body.appendChild(div);
                focus.innerHTML = '|';
                focus.style.cssText = 'display:inline-block;width:0px;overflow:hidden;z-index:-100;word-wrap:break-word;word-break:break-all;';
                div.className = this._cloneStyle(elem);
                div.style.cssText = 'visibility:hidden;display:inline-block;position:absolute;z-index:-100;word-wrap:break-word;word-break:break-all;overflow:hidden;';
            };
            div.style.left = this._offset(elem).left + "px";
            div.style.top = this._offset(elem).top + "px";
            var strTmp = elem.value.substring(0, index).replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br/>').replace(/\s/g, none);
            text.innerHTML = strTmp;

            focus.style.display = 'inline-block';
            try { focusOffset = this._offset(focus); } catch (e) { };
            focus.style.display = 'none';
            return {
                left: focusOffset.left,
                top: focusOffset.top,
                bottom: focusOffset.bottom
            };
        }
    },

    _cloneStyle: function (elem, cache) {
        if (!cache && elem['${cloneName}']) return elem['${cloneName}'];
        var className, name, rstyle = /^(number|string)$/;
        var rname = /^(content|outline|outlineWidth)$/;
        var cssText = [], sStyle = elem.style;

        for (name in sStyle) {
            if (!rname.test(name)) {
                val = this._getStyle(elem, name);
                if (val !== '' && rstyle.test(typeof val)) {
                    name = name.replace(/([A-Z])/g, "-$1").toLowerCase();
                    cssText.push(name);
                    cssText.push(':');
                    cssText.push(val);
                    cssText.push(';');
                };
            };
        };
        cssText = cssText.join('');
        elem['${cloneName}'] = className = 'clone' + (new Date).getTime();
        this._addHeadStyle('.' + className + '{' + cssText + '}');
        return className;
    },

    _addHeadStyle: function (content) {
        var style = this._style[document];
        if (!style) {
            style = this._style[document] = document.createElement('style');
            document.getElementsByTagName('head')[0].appendChild(style);
        };
        style.styleSheet && (style.styleSheet.cssText += content) || style.appendChild(document.createTextNode(content));
    },
    _style: {},

    _getStyle: 'getComputedStyle' in window ? function (elem, name) {
        return getComputedStyle(elem, null)[name];
    } : function (elem, name) {
        return elem.currentStyle[name];
    },

    _getFocus: function (elem) {
        var index = 0;
        if (document.selection) {
            elem.focus();
            var Sel = document.selection.createRange();
            if (elem.nodeName === 'TEXTAREA') {
                var Sel2 = Sel.duplicate();
                Sel2.moveToElementText(elem);
                var index = -1;
                while (Sel2.inRange(Sel)) {
                    Sel2.moveStart('character');
                    index++;
                };
            }
            else if (elem.nodeName === 'INPUT') {
                Sel.moveStart('character', -elem.value.length);
                index = Sel.text.length;
            }
        }
        else if (elem.selectionStart || elem.selectionStart == '0') {
            index = elem.selectionStart;
        }
        return (index);
    },

    _offset: function (elem) {
        var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement;
        var clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0;
        var top = box.top + (self.pageYOffset || docElem.scrollTop) - clientTop, left = box.left + (self.pageXOffset || docElem.scrollLeft) - clientLeft;
        return {
            left: left,
            top: top,
            right: left + box.width,
            bottom: top + box.height
        };
    }
};

function showTopNotice(notice){
	var el = document.getElementById("topNotice");
	el.innerHTML = notice;
	el.style.display = "block";
	setTimeout(function(){fadeout(el, 1)},500);
}

function showVideo(vid, el, cid){
	vel = document.getElementById(vid);
	cel = document.getElementById(cid);
	el.style.display = "none";
	vel.style.display = "block";
}

function closeVideo(vid, sid){
	vel = document.getElementById(vid);
	sel = document.getElementById(sid);
	vel.style.display = "none";
	sel.style.display = "block";
}

function getBroswerInfo(){
	var Sys = {};
	var ua = navigator.userAgent.toLowerCase();
	var s;
	(s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
	(s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
	(s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
	(s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
	(s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
	
	if (Sys.ie) return ('IE ' + Sys.ie);
	if (Sys.firefox)return ('Firefox ' + Sys.firefox);
	if (Sys.chrome) return ('Chrome ' + Sys.chrome);
	if (Sys.opera) return ('Opera ' + Sys.opera);
	if (Sys.safari) return ('Safari ' + Sys.safari);
	return "未知浏览器";
}

function showPFeedbackBox(){
	showMessageBox("<div><div id=\"f_share\" style=\"float:none\" class=\"publishBoxOutline\"><textarea id=\"f_b\" class=\"publishBox\" onfocus=\"if(this.value=='请输入反馈信息……'){this.style.color='#000';this.value='';}\" onblur=\"if(this.value==''){this.style.color='#888';this.value='请输入反馈信息……'}\" oninput=\"checkWords(1);checkat(1);\" onpopertychange=\"checkWords(1);checkat(1);\">请输入反馈信息……</textarea><div class=\"shareTag\" id=\"f_shareTag\">转发<span class=\"cancelShareTag\" onclick=\"document.getElementById('f_shareTag').style.display='none';document.getElementById('f_shareRepost').innerHTML='';\">×</span></div><div id=\"f_shareRepost\" style=\"display: none;\"></div><div class=\"shareBoxIcons\"><div id=\"f_checkBox\" class=\"checkBox\"></div><div class=\"shareBoxIconsFace\" onclick=\"showFacesAction(1);return false;\"></div><div class=\"shareBoxIconsTopic\" onclick=\"insertTrend(document.getElementById('f_b'));\"></div><div class=\"floatClear\"></div></div><div class=\"floatClear\"></div></div><div id=\"f_faceDiv\"></div>",2,"关闭","发布",closeMessageBox,feedbackAction);
	var shareBox = document.getElementById('f_b');
	shareBox.focus();
	if(post){
		checkWords(1);
		if(shareBox.setSelectionRange){
			shareBox.setSelectionRange(0,0);
		}
		else if (shareBox.createTextRange) {
			var range = shareBox.createTextRange();
			range.collapse(true);
			range.moveEnd('character', 0);
			range.moveStart('character', 0);
			range.select();
		}
	}
}

function feedbackAction(){
	if(!document.getElementById('f_b').value){
		return false;
	}
	sendStatus(document.getElementById('f_b').value+" "+getBroswerInfo()+" @Sneezry #清爽版微博反馈#",document.getElementById('f_shareRepost').innerText,'',1);
	document.getElementById('f_shareTag').style.display='none';
	document.getElementById('f_shareRepost').innerHTML='';
	closeMessageBox();
	var el = document.getElementById("topNotice");
	el.innerHTML = "发布中……";
	el.style.display = "block";
}

function getThisItem(w){
	var scrollT = document.body.scrollTop || document.documentElement.scrollTop;
	scrollT = scrollT?scrollT:0;
	var items = document.getElementsByName("statePost");
	var i;
	var fe=-1;
	for(i=0; i<items.length; i++){
		if(items[i].offsetTop-40 > scrollT && items[i+1] && w){
			return items[i].offsetTop-40;
		}
		else if(i>0 && items[i].offsetTop-40 >= scrollT && !w){
			return items[i-1].offsetTop-40;
		}
	}
	return 0;
}

function doScroll(pos, w){
	scrolling = true;
	var thisPos = document.body.scrollTop || document.documentElement.scrollTop;
	if(1==w){
		thisPos+=(pos-thisPos)/2.4;
	}
	else{
		thisPos-=(thisPos-pos)/2.4;
	}
	if((pos-thisPos<=5 || thisPos>=pos) && 1==w){
		document.body.scrollTop = pos;
		document.documentElement.scrollTop = pos;
		scrolling = false;
	}
	else if((thisPos-pos<=5 || thisPos<=pos) && 0==w){
		document.body.scrollTop = pos;
		document.documentElement.scrollTop = pos;
		scrolling = false;
	}
	else{
		document.body.scrollTop = thisPos;
		document.documentElement.scrollTop = thisPos;
		setTimeout(function(){doScroll(pos, w)}, 40);
	}
}

function pressToTop(){
	if(isgpressed){
		isgpressed = false;
		goToTop();
	}
	else{
		isgpressed = true;
		setTimeout(function(){isgpressed = false;},300);
	}
}

function goToTop(acceleration, time) {
	acceleration = acceleration || 0.1;
	time = time || 16;

	var dx = 0;
	var dy = 0;
	var bx = 0;
	var by = 0;
	var wx = 0;
	var wy = 0;

	if (document.documentElement) {
		dx = document.documentElement.scrollLeft || 0;
		dy = document.documentElement.scrollTop || 0;
	}
	if (document.body) {
		bx = document.body.scrollLeft || 0;
		by = document.body.scrollTop || 0;
	}
	var wx = window.scrollX || 0;
	var wy = window.scrollY || 0;

	var x = Math.max(wx, Math.max(bx, dx));
	var y = Math.max(wy, Math.max(by, dy));

	var speed = 1 + acceleration;
	window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));
	if(x > 0 || y > 0) {
		var invokeFunction = "goToTop(" + acceleration + ", " + time + ")"
		window.setTimeout(invokeFunction, time);
	}
}

function getNewWeibo(count){
	var latestWeibo = document.getElementsByName("statePost");
	latestWeibo = latestWeibo?latestWeibo[0]:null;
	var latestId = latestWeibo?latestWeibo.id:null;
	latestId = latestId?latestId.substr(5):0;
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		if(xmlhttp.responseText && xmlhttp.responseText.length>10){
  			document.getElementById("newPost").innerHTML = xmlhttp.responseText + document.getElementById("newPost").innerHTML;
  			insertNew();
  			setTimeout(function(){insertNew();document.getElementById("newpostnotice").style.display="block";unreadPost=true;}, 100);
  		}
		}
	}
	xmlhttp.open("GET","/getnewweibp.php?id="+latestId+"&count="+count);
	xmlhttp.send();
}

function insertNew(){
	var newWeibo = document.getElementById("newPost");
	newWeibo.style.display = "block";
	newWeiboHeight = newWeibo.offsetHeight;
	newWeibo.style.display = "none";
} 

function pullup(el, h, oh){
	h += h/1.2;
	if(h>oh){
		el.style.overflow = "visible";
		el.style.height = "auto";
		fadein(el,0);
		return;
	}
	else{
		el.style.height = h+"px";
		setTimeout(function(){pullup(el, h, oh);}, 40);
	}
}

function fadein(el,o){
	el.style.opacity = o;
	el.style.filter = "Alpha(opacity="+o*10+")";
	o+=0.1;
	el.style.visibility = "visible";
	if(o<0.9){
		setTimeout(function(){fadein(el,o);},40);
	}
	else{
		el.style.opacity = 1;
		el.style.filter = "Alpha(opacity=10)";
	}
}

function showNewPost(){
	var newWeibo = document.getElementById("newPost");
	var newHtml = "<div name=\"newPost\" style=\"visibility:hidden; height:0; overflow:hidden;\">" + newWeibo.innerHTML + "</div>";
	newWeibo.innerHTML = "";
	var newPostEl = document.createElement("div");
	newPostEl.innerHTML = newHtml;
	var timeLine = document.getElementById("timeLine");
	var latestPost = timeLine.getElementsByTagName("div")[0];
	if(latestPost){
		timeLine.insertBefore(newPostEl,latestPost);
	}
	else{
		timeLine.appendChild(newPostEl);
	}
	setTimeout(function(){pullup(document.getElementsByName("newPost")[0], 10, newWeiboHeight);},100);
}

function showMoreComments(postId){
	var el = document.getElementById("topNotice");
	el.innerHTML = "载入中……";
	el.style.display = "block";
	var xmlhttp;
	if(window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();
	}
	else{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function(){
  	if (xmlhttp.readyState==4 && xmlhttp.status==200){
  		showTopNotice("载入中……");
  		if(!xmlhttp.responseText){
  			return;
  		}
  		else{
  	  	document.getElementById("comment_line_"+postId).innerHTML = xmlhttp.responseText;
  	  	document.getElementById("show_more_comments_"+postId).style.display = "none";
  	  	if(document.getElementById("show_all_comments_"+postId)){
  	  		document.getElementById("show_all_comments_"+postId).style.display = "block";
  	  	}
  	  }
		}
	}
	xmlhttp.open("GET","/comments.php?request=1&count=10&post="+postId);
	xmlhttp.send();
}

function setElCenter(el){
	if(!el){
		return;
	}
	var wHHeight = (window.innerHeight || document.documentElement.clientHeight || document.body.offsetHeight)/2;
	var ae = el.offsetTop + wHHeight;
	document.body.scrollTop = ae;
	document.documentElement.scrollTop = ae;
}

function setCookie(c_name, value, expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function pulldown(el, h){
	el.style.overflow = "hidden";
	h -= (450-h)/1.5;
	if(h<10){
		el.style.height = "0";
		el.style.display = "none";
		el.style.visibility = "hidden";
		return;
	}
	else{
		el.style.height = h+"px";
		setTimeout(function(){pulldown(el, h);}, 40);
	}
}

function initCanvas(){
	canvas = document.getElementById('mainCanvas');
	if (canvas && canvas.getContext) {
		context = canvas.getContext('2d');
		if (context) {
			context.fillStyle = '#FFFFFF';
			context.fillRect(0, 0, 400, 300);
		}
	}
}

function clickCanvas(e){
	if (!e) {
		e = window.event;
	}
	lastMouseX = e.clientX;
	lastMouseY = e.clientY;
	drawLine = true;
	e.preventDefault();
	e.stopPropagation();
}

function drawCanvas(e){
	if(!drawLine){
		return;
	}
	if (!e) {
		e = window.event;
	}
	context.lineWidth = 2;
	context.strokeStyle = "#000000";
	context.beginPath();
	context.moveTo(lastMouseX-canvasLeft, lastMouseY-canvasTop);
	context.lineTo(e.clientX-canvasLeft, e.clientY-canvasTop);
	context.stroke();
	context.closePath();
	lastMouseX = e.clientX;
	lastMouseY = e.clientY;
}

function releaseCanvas(){
	drawLine = false;
}

function getCanvasImage(){
	var url = canvas.toDataURL("image/png");
	hideCanvas();
	getimage(url);
	showimagetag();
}

function hideCanvas(){
	document.getElementById("canvasDiv").style.display = "none";
	context.fillStyle = '#FFFFFF';
	context.fillRect(0, 0, 400, 300);
}

function clearCanvas(){
	context.fillStyle = '#FFFFFF';
	context.fillRect(0, 0, 400, 300);
}

function doSearch(q){
	q = "base64:"+Base64.encode(q).replace(/\+/g, "%252B");
	location.href='/search/'+q;
}

document.addEventListener("mousemove", drawCanvas, false);
document.addEventListener("mouseup", releaseCanvas, false);

var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64DecodeChars = new Array(　　 - 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 　　 - 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 　　 - 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 　　52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, 　　 - 1, 　0, 　1, 　2, 　3, 4, 　5, 　6, 　7, 　8, 　9, 10, 11, 12, 13, 14, 　　15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, 　　 - 1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 　　41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
function base64encode(str) {　　
	var out, i, len;　　
	var c1, c2, c3;　　len = str.length;　　i = 0;　　out = "";　　
	while (i < len) {
		c1 = str.charCodeAt(i++) & 0xff;
		if (i == len) {
			out += base64EncodeChars.charAt(c1 >> 2);　　out += base64EncodeChars.charAt((c1 & 0x3) << 4);　　out += "==";　　
			break;
		}
		c2 = str.charCodeAt(i++);
		if (i == len) {　　out += base64EncodeChars.charAt(c1 >> 2);　　out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));　　out += base64EncodeChars.charAt((c2 & 0xF) << 2);　　out += "=";　　
			break;
		}
		c3 = str.charCodeAt(i++);
		out += base64EncodeChars.charAt(c1 >> 2);
		out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
		out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
		out += base64EncodeChars.charAt(c3 & 0x3F);　　
	}　　
	return out;
}
function base64decode(str) {　　
	var c1, c2, c3, c4;　　
	var i, len, out;　　len = str.length;　　i = 0;　　out = "";　　
	while (i < len) {
		/* c1 */
		do {　　c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
		} while ( i < len && c1 == - 1 );
		if (c1 == -1)　　
		break;
		/* c2 */
		do {　　c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
		} while ( i < len && c2 == - 1 );
		if (c2 == -1)　　
		break;
		out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
		/* c3 */
		do {　　c3 = str.charCodeAt(i++) & 0xff;　　
			if (c3 == 61)　
			return out;　　c3 = base64DecodeChars[c3];
		} while ( i < len && c3 == - 1 );
		if (c3 == -1)　　
		break;
		out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
		/* c4 */
		do {　　c4 = str.charCodeAt(i++) & 0xff;　　
			if (c4 == 61)　
			return out;　　c4 = base64DecodeChars[c4];
		} while ( i < len && c4 == - 1 );
		if (c4 == -1)　　
		break;
		out += String.fromCharCode(((c3 & 0x03) << 6) | c4);　　
	}　　
	return out;
}
function utf16to8(str) {　　
	var out, i, len, c;　　out = "";　　len = str.length;　　
	for (i = 0; i < len; i++) {
		c = str.charCodeAt(i);
		if ((c >= 0x0001) && (c <= 0x007F)) {　　out += str.charAt(i);
		} else if (c > 0x07FF) {　　out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));　　out += String.fromCharCode(0x80 | ((c >> 　6) & 0x3F));　　out += String.fromCharCode(0x80 | ((c >> 　0) & 0x3F));
		} else {　　out += String.fromCharCode(0xC0 | ((c >> 　6) & 0x1F));　　out += String.fromCharCode(0x80 | ((c >> 　0) & 0x3F));
		}　　
	}　　
	return out;
}
function utf8to16(str) {　　
	var out, i, len, c;　　
	var char2, char3;　　out = "";　　len = str.length;　　i = 0;　　
	while (i < len) {
		c = str.charCodeAt(i++);
		switch (c >> 4) {　
		case 0:
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
		case 6:
		case 7:
			　　 // 0xxxxxxx 
			　　out += str.charAt(i - 1);　　
			break;　
		case 12:
		case 13:
			　　 // 110x xxxx　 10xx xxxx 
			　　char2 = str.charCodeAt(i++);　　out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));　　
			break;　
		case 14:
			　　 // 1110 xxxx　10xx xxxx　10xx xxxx 
			　　char2 = str.charCodeAt(i++);　　char3 = str.charCodeAt(i++);　　out += String.fromCharCode(((c & 0x0F) << 12) | 　　　　 ((char2 & 0x3F) << 6) | 　　　　 ((char3 & 0x3F) << 0));　　
			break;
		}
	}　　
	return out;
}

function whover(elid, hmid){
	hmenu[hmid] = true;
	if(hmenu[hmid]){
		document.getElementById(elid).style.display = 'block';
	}
	else{
		return;
	}
}

function whout(elid, hmid){
	hmenu[hmid] = false;
}

function showSidebarQuestion(qid){
	if(!qid){
		return;
	}
	var qtext;
	switch(qid){
		case 1: qtext = "通过转发一条微博帮助清爽版微博请求分组API权限。由于新浪微博开放平台不对外开放分组API，而只对特定应用开发分组API，所以清爽版微博一直未能提供好友分组功能，如果您也希望清爽版微博能提供此功能，请帮助清爽版微博号召新浪微博开放平台开放分组API权限。";break;
		case 2: qtext = "发布一条微博向我的好友推荐清爽版微博，发布的微博内容为『我正在使用清爽版微博，清新的界面，绝佳的阅读体验，让你感受到阅读的真正乐趣，你也来一起体验吧！http://qingshuang.sinaapp.com/』";break;
		case 3: qtext = "通过支付宝向清爽版微博捐助任意金额捐款以帮助开发者完善应用，您需要一个支付宝帐号和一个支持网上付款的银行卡。";
	}
	showMessageBox(qtext,1,null,"确定",null,closeMessageBox);
}

function callGroup(){
	postnew(null, "3481970900338041");
	thanks4Support();
}

function recommend2Friends(){
	postnew("我正在使用清爽版微博，清新的界面，绝佳的阅读体验，让你感受到阅读的真正乐趣，你也来一起体验吧！http://qingshuang.sinaapp.com/");
	thanks4Support();
}

function thanks4Support(){
	showMessageBox("感谢您的支持，清爽版微博有您的支持才变得如此完美！",0,"关闭",null,closeMessageBox,null);
}

document.onclick = function(){
	if(!hmenu[0]){
		document.getElementById('cmtmenu').style.display = 'none';
	}
	if(!hmenu[1]){
		document.getElementById('mtnmenu').style.display = 'none';
	}
}